<template>
  <HeadContainer class="tag-list bg-background" :title="tag" :divider="false" @back="back" full disable-tail-gap>
    <ScrollTabView v-model="media" :tab-options="TAB_MEDIA" :height-trim-rem="3" @load="nextPage">
      <template #outer-tabs>
        <div v-if="tagDesc" class="tag-desc pointer" @click="tagDescFold = !tagDescFold">
          <p class="font-size-12 font-weight-500 line-height-120" :class="{ fold: tagDescFold }">{{ tagDesc }}</p>
        </div>
      </template>
      <template #tab-content-1>
        <MediaRow
          class="px-4"
          :items="fetchers.video.dataList"
          :loading="fetchers.video.loading"
          :no-more="fetchers.video.noMore"
          @click:item="onItemClick"
        ></MediaRow>
      </template>
      <template #tab-content-2>
        <MediaRow
          class="px-4"
          :items="fetchers.photo.dataList"
          :loading="fetchers.photo.loading"
          :no-more="fetchers.photo.noMore"
          @click:item="onItemClick"
        ></MediaRow>
      </template>
    </ScrollTabView>
  </HeadContainer>
  <Jsonld :schema="schema" :active="active"></Jsonld>
</template>

<script setup>
import { computed, inject, provide, ref, shallowRef, watch, watchEffect } from 'vue'
import { useCreatorStore } from '@/store/creator'
import { useHeadStore } from '@/store/head'
import { $t } from '@/i18n'
import { toDate } from '@/utils/string-helper'
import Jsonld from '@/components/common/Jsonld.vue'
import HeadContainer from '@/components/layout/HeadContainer.vue'
import ScrollTabView from '@/components/layout/ScrollTabView.vue'
import MediaRow from '@/components/media/MediaRow.vue'
import { useBack } from '@/compositions/viewer/back'
import { useDialog } from '@/compositions/viewer/dialog'
import { AD_TYPE } from '@/constant'
import { TAB_MEDIA } from '@/constant/config'
import { MEDIA_TYPE_LABELS } from '@/constant/viewer-router'

// 提供 eventId 给 MediaColumn使用
provide('adEventId', 66)

const props = defineProps({
  index: { type: Number, required: true },
  active: { type: Boolean },
  tag: { type: String },
})

const emits = defineEmits(['back'])

const viewerRouter = inject('viewerRouter')
const { nextToIndexedViewer, getMediaType, getVideoFetcher, getPhotoFetcher } = viewerRouter

const back = useBack(viewerRouter, () => emits('back'), 'tag')

const media = getMediaType(props.index)
const fetchers = {
  video: getVideoFetcher(props.index),
  photo: getPhotoFetcher(props.index),
}

const tagTitle = computed(() => fetchers[MEDIA_TYPE_LABELS[media.value]].dataExtra?.tag?.sub_title || props.tag)
const tagDesc = computed(() => fetchers[MEDIA_TYPE_LABELS[media.value]].dataExtra?.tag?.content)
const tagKeywords = computed(() => fetchers[MEDIA_TYPE_LABELS[media.value]].dataExtra?.tag?.meta_keywords)
const tagDescFold = ref(true)

const nextPage = () => fetchers[MEDIA_TYPE_LABELS[media.value]]?.nextPage()

const { subscribe, shopBuy } = useDialog()
const { getCreator } = useCreatorStore()

async function onItemClick(index) {
  const item = fetchers[MEDIA_TYPE_LABELS[media.value]].dataList[index]

  // 訂閱
  if (item.need_subscribe) {
    const creator = await getCreator(item.author.aff)
    subscribe({
      item: {
        author: {
          aff: item.author.aff,
          avatar: item.author.avatar,
          nickname: item.author.nickname,
          username: item.author.username,
          price: creator.subscribe_price,
        },
        id: item.id,
      },
      gtmKey: 27,
    })
  }

  // 購買單筆帖子
  else if (item.need_buy) {
    shopBuy(item)
  }

  // 前往下一頁播放器
  else {
    nextToIndexedViewer(index)
  }
}

const { toTagHead } = useHeadStore()
watchEffect(() => {
  const title = tagTitle.value
  const description = tagDesc.value
  const keywords = tagKeywords.value
  if (props.active) {
    toTagHead({ title, description, keywords })
  }
})
watch(
  () => props.active,
  (v) => {
    if (v) {
      toTagHead({ title: tagTitle.value, description: tagDesc.value, keywords: tagKeywords.value })
    }
  },
  { immediate: true },
)

// Jsonld 佈置
const schema = shallowRef(null)
watchEffect(() => {
  const name = tagTitle.value
  const description = tagDesc.value
  const videoList = fetchers.video.dataList
    .filter((v) => v.type !== AD_TYPE.VIDEO && v.type !== AD_TYPE.PHOTO)
    .map((v) => ({
      '@type': 'VideoObject',
      // position: 1,
      name: v.content,
      // description: '這是與 {tag_name} 標籤相關的影片 {video_title1}。',
      thumbnailUrl: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
      uploadDate: toDate(v.display_at).toISOString(),
      duration: v.video_time,
      contentUrl: v.share_url.replace(/\?share_aff=\d*/, ''),
      interactionStatistic: {
        '@type': 'InteractionCounter',
        interactionType: 'https://schema.org/LikeAction',
        userInteractionCount: v.like,
      },
      author: {
        '@type': 'Person',
        name: v.author.nickname,
        alternateName: v.author.username,
        identifier: `${v.author.aff}`,
      },
      publisher: {
        '@type': 'Organization',
        name: 'Fantasi',
        logo: {
          '@type': 'ImageObject',
          url: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
        },
      },
      keywords: v.tags + ',' + $t('meta.keywords.short'),
    }))
  const photoList = fetchers.photo.dataList
    .filter((v) => v.type !== AD_TYPE.VIDEO && v.type !== AD_TYPE.PHOTO)
    .map((v) => ({
      '@type': 'ImageObject',
      // position: 1,
      name: v.content,
      // description: '這是與 {tag_name} 標籤相關的影片 {video_title1}。',
      thumbnailUrl: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
      uploadDate: toDate(v.display_at).toISOString(),
      contentUrl: v.share_url.replace(/\?share_aff=\d*/, ''),
      interactionStatistic: {
        '@type': 'InteractionCounter',
        interactionType: 'https://schema.org/LikeAction',
        userInteractionCount: v.like,
      },
      author: {
        '@type': 'Person',
        name: v.author.nickname,
        alternateName: v.author.username,
        identifier: `${v.author.aff}`,
      },
      publisher: {
        '@type': 'Organization',
        name: 'Fantasi',
        logo: {
          '@type': 'ImageObject',
          url: import.meta.env.VITE_APP_URL + import.meta.env.VITE_APP_OG_IMAGE,
        },
      },
      keywords: v.tags + ',' + $t('meta.keywords.content'),
    }))
  schema.value = {
    '@context': 'https://schema.org',
    '@type': 'ItemList',
    name,
    description,
    itemListOrder: 'http://schema.org/ItemListOrderAscending',
    itemListElement: [...videoList, ...photoList],
  }
})
</script>

<style lang="scss" scoped>
.tag-list {
  width: 100%;
  height: 100%;

  .tag-desc {
    width: calc(100% - 2rem);
    margin: auto;
    padding: 0.625rem 1rem;
    border-radius: 0.625rem;
    background: black;
    text-align: justify;

    p.fold {
      overflow: hidden;
      display: -webkit-box;
      -webkit-line-clamp: 3;
      -webkit-box-orient: vertical;
    }
  }
}
</style>
